package com.huangjue.backend.controller;

import com.huangjue.backend.entity.Student;
import com.huangjue.backend.entity.Teacher;
import com.huangjue.backend.entity.User;
import com.huangjue.backend.dto.UserRegisterRequest;
import com.huangjue.backend.service.MessageService;
import com.huangjue.backend.service.UserService;
import com.huangjue.backend.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private StudentService studentService;

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        String email = loginRequest.get("email");
        String password = loginRequest.get("password");

        // 打印收到的参数
        System.out.println("Received email: " + email);
        System.out.println("Received password: " + password);

        Map<String, Object> response = new HashMap<>();
        
        if (email == null || password == null) {
            response.put("success", false);
            response.put("message", "邮箱和密码不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        User user = userService.login(email, password);
        Student student= studentService.getStudentByUserId(user.getUserId());
        if (user != null) {
            response.put("success", true);
            response.put("message", "登录成功");
            // 生成简单的token（实际项目中应该使用JWT）
            response.put("token", "token_" + user.getUserId() + "_" + System.currentTimeMillis());
            response.put("user",user);
            response.put("student",student);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "邮箱或密码错误");

            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody UserRegisterRequest registerRequest) {
        // 打印收到的参数
        System.out.println("Received register request: " + registerRequest);

        Map<String, Object> response = new HashMap<>();

        // 参数验证
        if (registerRequest.getEmail() == null || registerRequest.getPassword() == null ||
                registerRequest.getNickname() == null) {
            response.put("success", false);
            response.put("message", "必填字段不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 执行注册
        boolean registerResult = userService.register(registerRequest);

        if (registerResult) {
            response.put("success", true);
            response.put("message", "注册成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "注册失败，邮箱可能已存在");
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "退出登录成功");
        return ResponseEntity.ok(response);
    }

    // 获取用户信息（含扩展信息）
    @GetMapping("/info/{userId}")
    public ResponseEntity<Map<String, Object>> getUserInfo(@PathVariable Integer userId) {
        Map<String, Object> response = new HashMap<>();
        User user = userService.getUserById(userId);
        com.huangjue.backend.entity.Student student = studentService.getStudentByUserId(userId);
        if (user != null) {
            response.put("success", true);
            response.put("data", user);
            response.put("student", student);
        } else {
            response.put("success", false);
            response.put("message", "用户不存在");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 获取当前用户信息（通过token）
     */
    @GetMapping("/auth/user")
    public ResponseEntity<Map<String, Object>> getCurrentUserInfo(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.put("success", false);
            response.put("message", "未登录或token无效");
            return ResponseEntity.status(401).body(response);
        }
        // 简单token解析：token_xxx_userId_xxx
        String[] parts = token.split("_");
        if (parts.length < 2) {
            response.put("success", false);
            response.put("message", "token格式错误");
            return ResponseEntity.status(401).body(response);
        }
        Integer userId;
        try {
            userId = Integer.parseInt(parts[1]);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "token解析失败");
            return ResponseEntity.status(401).body(response);
        }
        User user = userService.getUserById(userId);
        Student student=studentService.getStudentByUserId(userId);
        Map<String, Object> data = new HashMap<>();
        data.put("user", user);       // 放入用户信息
        data.put("student", student); // 放入学生认证信息
        if (user != null) {
            response.put("success", true);
            response.put("data", data);
        } else {
            response.put("success", false);
            response.put("message", "用户不存在");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 更新当前用户名
     */
    @PostMapping("/updateUsername")
    public ResponseEntity<Map<String, Object>> updateCurrentStudentInfo(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        boolean result = userService.updateUsername(user);
        response.put("success", result);
        response.put("message", result ? "更新成功" : "更新失败");
        return ResponseEntity.ok(response);
    }

    //学生认证
    @PostMapping("/studentAuth")
    public ResponseEntity<Map<String, Object>> studentAuth(@RequestBody Student student) {
        Map<String, Object> response = new HashMap<>();
        boolean result = userService.studentAuth(student);
        response.put("success", result);
        response.put("message", result ? "认证信息已提交，待审核" : "认证提交失败");
        return ResponseEntity.ok(response);
    }

    /*
    * 首页教师展示
    * */
    @GetMapping("/recommendTeacher")
    public ResponseEntity<Map<String, Object>> getRecommendTeacher() {
        Map<String, Object> response = new HashMap<>();

        try {
            List<Teacher> recommendTeachers = userService.getRecommendTeacher();
            response.put("success", true);
            response.put("message", "获取推荐老师成功");
//            System.out.println("推荐老师测试成了！！~！！");
            response.put("data", recommendTeachers);
//            System.out.println("推荐老师结果展示111"+response);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取推荐老师失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/changePassword")
    public ResponseEntity<Map<String, Object>> changePassword(@RequestBody Map<String, Object> req) {
        Integer userId = (Integer) req.get("userId");
        String oldPassword = (String) req.get("oldPassword");
        String newPassword = (String) req.get("newPassword");
        Map<String, Object> response = new HashMap<>();
        boolean result = userService.changePassword(userId, oldPassword, newPassword);
        response.put("success", result);
        response.put("message", result ? "密码修改成功" : "原密码错误或修改失败");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改邮箱
     */
    @PostMapping("/changeEmail")
    public ResponseEntity<Map<String, Object>> changeEmail(@RequestBody Map<String, Object> req) {
        Integer userId = (Integer) req.get("userId");
        String newEmail = (String) req.get("newEmail");
        String password = (String) req.get("password");
        Map<String, Object> response = new HashMap<>();
        boolean result = userService.changeEmail(userId, newEmail, password);
        response.put("success", result);
        response.put("message", result ? "邮箱修改成功" : "邮箱修改失败");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/teacher/{teacherId}")
    public ResponseEntity<Map<String, Object>> getTeacherById(@PathVariable Integer teacherId) {
        Map<String, Object> response = new HashMap<>();
        try {
            Teacher teacher = userService.getTeacherById(teacherId);
            if (teacher != null) {
                response.put("success", true);
                response.put("data", teacher);
            } else {
                response.put("success", false);
                response.put("message", "老师不存在");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取老师信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    @GetMapping("/teacher/recommend/{recommendId}")
    public ResponseEntity<Map<String, Object>> getTeacherIdByRecommendId(@PathVariable Integer recommendId) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer teacherId = userService.getTeacherIdByRecommendId(recommendId);
            if (teacherId != null) {
                response.put("success", true);
                response.put("data", teacherId);
            } else {
                response.put("success", false);
                response.put("message", "推荐教师不存在");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取教师ID失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 给教师送花
     */
    @PostMapping("/teacher/flower/{teacherId}")
    public ResponseEntity<Map<String, Object>> sendFlowerToTeacher(@PathVariable Integer teacherId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = userService.sendFlowerToTeacher(teacherId);
            response.put("success", success);
            response.put("message", success ? "送花成功" : "送花失败");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "送花失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

}